import SockJS from 'sockjs-client';
import Stomp, { Client, Frame } from 'stompjs';

export default class WebSocketUtil {
    private static connected = false;
    private static client: Client | undefined;

    public static isConnected() {
        return this.connected;
    }

    public static connect(headers: any, callback?: (frame?: Frame) => any, errCallback?: (err: Frame | string) => any) {
        if (this.connected) {
            callback?.();
            return;
        }
        // const sockjs = new SockJS('http://localhost:60001/ws');
        // const client = Stomp.over(sockjs);
        this.client = Stomp.client(`ws://localhost:60002/ws`);
        this.client.connect(
            headers,
            (frame) => {
                this.connected = true;
                callback?.(frame);
            },
            (err) => {
                this.client = undefined;
                this.connected = false;
                errCallback?.(err);
            }
        );
    }

    public static disconnect(callback?: () => any) {
        if (this.client) {
            this.client.disconnect(() => {
                this.client = undefined;
                this.connected = false;
                callback?.();
            });
        } else {
            this.connected = false;
            callback?.();
        }
    }

    public static async send(msg: string) {
        this.client?.send('/hello', {}, msg);
    }
}
